import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { client, queryClient } from '@fill/client';
import { notification } from 'antd';
import { useContext } from 'react';
import { CONFIG_KEYS } from '../../constants/config';
import { FillContext } from './Fill';

interface IFormParams {
  origin_password: string
  password: string
  confirm_password: string
}

export const Password = () => {
  const { onLogout, config } = useContext(FillContext);
  async function handleUpdatePassword({
    origin_password,
    password,
  }: IFormParams) {
    if (String(origin_password) !== String(config[CONFIG_KEYS.PASSWORD])) {
      console.log(config);
      notification.error({
        message: '原密码匹配失败',
      });
      return false;
    }

    try {
      await queryClient.fetchQuery({
        queryFn: () => client.mutation(['configs.save', {
          arg: {
            key: CONFIG_KEYS.PASSWORD,
            value: password,
          },
        }]),
      });

      await queryClient.refetchQueries({
        queryKey: ['configs.all'],
      });

      onLogout();
    }
    catch (error) {
      notification.error({
        message: '修改失败',
      });
    }

    return true;
  }

  return (
    <>
      <div style={{
        display: 'flex',
        flexDirection: 'row-reverse',
        paddingBottom: 12,
      }}>
        <ModalForm<{
          origin_password: string
          password: string
          confirm_password: string
        }>
          trigger={
            <a key="password">修改密码</a>
          }
          modalProps={{
            destroyOnClose: true,
          }}
          title="修改密码"
          width={400}
          onFinish={handleUpdatePassword}
        >
          <br />
          <ProFormText.Password label="原密码" name="origin_password" rules={[{ required: true, message: '请输入原密码' }]} />
          <ProFormText.Password label="密码" name="password" rules={[{ required: true, message: '请输入新密码' }]} />
          <ProFormText.Password label="确认密码" name="confirm_password" dependencies={['password']} rules={[
            {
              required: true,
              message: '请输入确认密码!',
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value)
                  return Promise.resolve();

                return Promise.reject(new Error('两次输入不匹配!'));
              },
            }),
          ]} />
        </ModalForm>
      </div>
    </>
  );
};
